package com.yunhan.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * SpringSecurity工具类
 */
public class SecurityUtils {

    /**
     * 获取当前登录用户名
     */
    public static String getUsername(){
        SecurityUser user = SecurityUtils.getUser();
        if (null == user)
            return null;
        return user.getUsername();
    }
    /**
     * 获取当前登录部门id
     */
    public static Long getDeptId(){
        SecurityUser user = SecurityUtils.getUser();
        if (null == user)
            return null;
        return user.getDeptId();
    }
    /**
     * 获取当前登录用户id
     */
    public static Long getUid() {
        SecurityUser user = SecurityUtils.getUser();
        if (null == user)
            return null;
        return user.getId();
    }

    /**
     * 获取当前登录用户信息
     */
    public static SecurityUser getUser(){
        Authentication authentication = SecurityUtils.getAuthentication();
        if (null == authentication)
            return null;
        Object details = authentication.getDetails();
        if ( details instanceof  SecurityUser)
            return (SecurityUser) details;
        return null;
    }

    public static Authentication getAuthentication(){
        SecurityContext context = SecurityContextHolder.getContext();
        return context.getAuthentication();
    }
}
